package com.ylkj.wx.controller;

import java.io.IOException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import com.ylkj.wx.constant.WeiXConstant;
import com.ylkj.wx.dto.UnifiedOrderDto;
import com.ylkj.wx.entitis.BizInfoEntity;
import com.ylkj.wx.entitis.EmployeeEntity;
import com.ylkj.wx.entitis.EvaluateInfoEntity;
import com.ylkj.wx.entitis.OrderEntity;
import com.ylkj.wx.form.RewardForm;
import com.ylkj.wx.service.BizInfoService;
import com.ylkj.wx.service.EmployeeInfoService;
import com.ylkj.wx.service.EvaluateService;
import com.ylkj.wx.service.OrderInfoService;
import com.ylkj.wx.utils.CommonUtil;
import com.ylkj.wx.utils.UUIDUtil;
import com.ylkj.wx.utils.WeixCommonUtil;

/**
 * 打赏功能
 * @author baoy
 *
 */
@Controller
@RequestMapping("/reward")
public class RewardController {
	private static final Logger logger = LoggerFactory.getLogger(RewardController.class);
	
	@Autowired
	private EmployeeInfoService employeeInfoService;
	
	@Autowired
	private BizInfoService bizInfoService;
	
	@Autowired
	private EvaluateService evaluateService;
	
	@Autowired
	private OrderInfoService orderInfoService;


	
	/**
	 * 进入打赏页面
	 * @param employeeId
	 * @return
	 */
	@RequestMapping("/rindex")  
    public ModelAndView questionList(String phrCode) {  
		ModelAndView mav = new ModelAndView();
		/*EmployeeInfoDTO employeeInfoDTO = employeeInfoService.fineOneEmployeeInfoById(Integer.parseInt(employeeId));
    	String bizCode = employeeInfoDTO.getBizCode();
    	BizInfoDTO bizInfoDTO = bizInfoService.fineOneBizInfoById(bizCode);
    	mav.setViewName("reward"); //返回的文件名  
    	mav.addObject("employeeInfoDTO",employeeInfoDTO); 
    	mav.addObject("bizInfoDTO",bizInfoDTO); */
		if("".equals(phrCode)){
    		mav.setViewName("rewardNoPerson"); //返回的文件名  
        	return mav; 
    	}
    	EmployeeEntity employeeInfoEntity = employeeInfoService.getEmployeeById(phrCode);
    	if(employeeInfoEntity==null){
    		mav.setViewName("rewardNoPerson"); //返回的文件名  
        	return mav; 
    	}
    	String bizCode = employeeInfoEntity.getBizCode();
    	BizInfoEntity bizInfoEntity = null;
    	if(bizCode!=null && !"".equals(bizCode)){
    		bizInfoEntity = bizInfoService.fineOneBizInfoByCode(bizCode);
    	}
    	mav.setViewName("reward"); //返回的文件名  
    	mav.addObject("employeeInfoDTO",employeeInfoEntity); 
    	mav.addObject("bizInfoDTO",bizInfoEntity); 
    	return mav; 
    } 
	
	
	/**
	 * 进入打赏页面
	 * @param employeeId
	 * @return
	 */
	@RequestMapping("/saveReward")  
    public ModelAndView saveReward(@ModelAttribute("form") RewardForm form,HttpServletRequest request,HttpServletResponse response) {  
		System.out.println("----come in ------");
		ModelAndView mav = new ModelAndView();
		String money = form.getMoney()==null?"0":form.getMoney();
		String selfMoney = form.getSelfMoney()==null?"0":form.getSelfMoney();
		if("-1".equals(money)){
			money = selfMoney;
		}
		double payMoney = Double.parseDouble(money);
		int score = (form.getScore()==null || "".equals(form.getScore()))?0:Integer.parseInt(form.getScore());
		String evaluteDetail = form.getEvaluteDetail()==null?"":form.getEvaluteDetail();
		String bizCode = form.getBizCode();
		String phrCode = form.getPhrCode();
		
		//保存评价信息
		if(!"".equals(score) || !"".equals(evaluteDetail)){
			EvaluateInfoEntity entity = new EvaluateInfoEntity();
			entity.setBizCode(bizCode);
			entity.setPhrCode(phrCode);
			entity.setStarNum(score);
			entity.setContent(evaluteDetail);
			evaluateService.saveEvaluateInfo(entity);
		}
		
		//保存打赏信息
		OrderEntity entityOrder = new OrderEntity();
		entityOrder.setBizCode(bizCode);
		String orderNo = UUIDUtil.getUUID();
					entityOrder.setPhrCode(phrCode);
					entityOrder.setPayMoney(payMoney);
					entityOrder.setPayMode("1");//1微信
					entityOrder.setOrderNo(orderNo);
					orderInfoService.saveorderInfo(entityOrder);
		
					System.out.println("1111-----begin");
					//微信统一下单
					UnifiedOrderDto unifiedorder = new UnifiedOrderDto();
					unifiedorder.setAppId(WeiXConstant.appid);
					unifiedorder.setMchId(WeiXConstant.mch_id);
					unifiedorder.setDeviceInfo(WeiXConstant.device_info);
					unifiedorder.setBody("reward order");
					String nonce = UUIDUtil.getUUID();
				    unifiedorder.setNonceStr(nonce);

				    System.out.println("1111---------------middel");
				    
			        unifiedorder.setNotifyUrl(WeiXConstant.domain_url+"order/wxPayCallBack");
			        unifiedorder.setTradeType(WeiXConstant.trade_type);
			        
				    //商户订单号 out_trade_no
			        unifiedorder.setOutTradeNo(orderNo);
			        //微信钱币以分为单位，所以乘100换算成元
			        //update by baoy on 20170804 
			        String totalFee = String.valueOf(Math.round(entityOrder.getPayMoney()*100));
			        //String totalFee = String.valueOf("100");
			        unifiedorder.setTotalFee(totalFee);
			        
			        unifiedorder.setSpbillCreateIp(CommonUtil.getIpAddr(request)); //获取访问IP
			        System.out.println("1111-----ip----------"+CommonUtil.getIpAddr(request));
			        //"wap_url": "",//WAP网站URL地址        "wap_name": ""  //WAP 网站名
			        unifiedorder.setSceneInfo("{\"h5_info\": {\"type\":\"Wap\",\"wap_url\": \"http://puyfg37476.jsp.cdnjsp.cn\",\"wap_name\": \"order1234556\"}}");
			        //unifiedorder.setOpenid(openId);
			        System.out.println("1111---------------chong dingxiang ");
			        unifiedorder = WeixCommonUtil.unifiedOrder(unifiedorder);
			        System.out.println("1111");
			        System.out.println(unifiedorder.getMwebUrl());
			        try {
						response.sendRedirect(unifiedorder.getMwebUrl());
					} catch (IOException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
		
			        
			        System.out.println("1111---------------end");
		
    	//mav.addObject("bizInfoDTO",bizInfoEntity); 
		mav.setViewName("rewardSuc");
    	return mav; 
    } 
}
